<script setup>
import {
  onBeforeUnmount,
  defineModel,
  defineProps,
  reactive,
  shallowRef,
  defineExpose
} from "vue"
import { Editor, Toolbar } from "@wangeditor/editor-for-vue"
import "@wangeditor/editor/dist/css/style.css" // 引入 css
import { useStore } from "vuex"
const store = useStore()

const props = defineProps({
  height: String,
  disabled: Boolean,
  onlyShow: {
    type: Boolean,
    default: false
  }
})

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = defineModel()

//定义模式
const mode = "default" // 或 'simple'

// 工具栏配置
const toolbarConfig = reactive({})

// 内容区配置项
const editorConfig = { placeholder: "请输入内容...", MENU_CONF: {} }
editorConfig.MENU_CONF["uploadImage"] = {
  server: `${
    process.env.NODE_ENV === "development" ? "/dev_api" : "/api"
  }/blog/file/upload`,
  fieldName: "file",
  headers: {
    Authorization: store.getters["user/token"]
  },
  // 上传之前触发
  onBeforeUpload(file) {
    return file
  },

  // 上传进度的回调函数
  onProgress(progress) {
    // onProgress(progress) {
    // progress 是 0-100 的数字
    console.log("progress", progress)
  },
  // 自定义插入图片
  customInsert(res, insertFn) {
    console.log(res, insertFn)
    // customInsert(res, insertFn) {
    // res 即服务端的返回结果
    let { filename } = res.files[0]
    // 从 res 中找到 url alt href ，然后插入图片
    // insertFn("http://localhost:3001/" + filename)
    insertFn(
      `http://${
        process.env.NODE_ENV === "development"
          ? "localhost:3001/"
          : "8.153.36.96/"
      }${filename}`
    )
  }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

// 记录 editor 实例
const handleCreated = (editor) => {
  editorRef.value = editor
  if (props.disabled) {
    editor.disable()
  }
  //打印所有默认配置
  console.log(editor.getConfig()["MENU_CONF"])
}

defineExpose({
  editorRef
})
</script>

<template>
  <div
    class="editor"
    :style="{ width: '100%', height: props.height || '70vh' }"
  >
    <Toolbar
      v-if="!onlyShow"
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>

<style lang="scss" scoped>
.editor {
  display: flex;
  flex-direction: column;
  border: 1px solid #ccc;
  div {
    &:last-child {
      flex: 1;
      overflow: auto;
    }
  }
}
</style>
